package com.d2.modules.system.permission.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.d2.common.domain.Result;

import com.d2.modules.system.permission.entity.*;
import com.d2.modules.system.permission.mapper.IUserRoleMapper;
import com.d2.modules.system.permission.service.IResourceService;
import com.d2.modules.system.permission.service.IRoleService;
import com.d2.modules.system.permission.service.IUserRoleService;
import com.d2.modules.system.permission.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("auth/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IResourceService menuService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;

//    @Autowired
//    private User user;


    @GetMapping("permissions")
    public Result<List<Resource>> menuTree(){
        return Result.success(this.menuService.permissionTree());
    }

    @GetMapping("page")
    public Result<Page<User>> page(Page<User> page){
        page = this.userService.page(page);
        page.getRecords().forEach(user -> {
            List<Role> roles = roleService.queryRoleByUserId(user.getId());
            List<Long> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
            user.setRoles(roleIds);
        });
        return Result.success(page);
    }


    @GetMapping("getAllRole")
    public Result<List<Role>> getAllRole(){
        return Result.success(roleService.list());
    }


    @PostMapping("update")
    public Result<Void> update(@RequestBody User obj){
        userService.updateById(obj);
        return Result.success();
    }


    @Transactional
    @PostMapping("authz")
    public Result<?> authz(Long userId, @RequestBody List<Long> list) {
        UserRole query = new UserRole();
        query.setUserId(userId);

        List<UserRole> userRoleList = new ArrayList<>();
        userRoleService.remove(new QueryWrapper<>(query));
        list.forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        });
        userRoleService.saveBatch(userRoleList);
        return Result.success();
    }
}
